package cloud.smalla.resolver;

import cloud.smalla.annotation.CurrenUser;
import cloud.smalla.utils.JwtUtils;
import cloud.smalla.utils.RedisUtils;
import cloud.smalla.vo.LoginUser;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Nonnull;
import javax.annotation.Resource;

/**
 * 功能描述
 * 来处理方法参数的解析器
 * 传递请求所对应的user信息
 *
 * @author 邱彦祥
 * 时间：2023-03-31 16:35
 */
@Component
public class UserInfoResolver implements HandlerMethodArgumentResolver {

    @Resource
    RedisUtils redisUtils;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrenUser.class);
    }

    @Override
    public LoginUser resolveArgument(@Nonnull MethodParameter methodParameter,
                                     ModelAndViewContainer modelAndViewContainer,
                                     NativeWebRequest nativeWebRequest,
                                     WebDataBinderFactory webDataBinderFactory) {
        //从请求头中获取token
        String jwt = nativeWebRequest.getHeader(JwtUtils.getHeader());
        //用token去Redis里面换取userInfo
        return (LoginUser) redisUtils.get("userInfo:" + jwt);
    }
}
